<?php
/**
 * Celebrio Kernel
 *
 * @copyright  Copyright (c) 2012 Celebio Software, s.r.o.
 * @package    Kernel
 */
namespace KernelModule\LogsModule\PerformanceModule;

use Nette\Object;
use Nette\Environment;
use Nette\String;

use KernelModule\LogsModule\PerformanceModule\IPerformanceLogs;

use Celebrio\FileSystem\TextFile;

/**
 * Azure performance logs in Celebrio
 * 
 * @author Martin Novák
 */
class PerformanceLogsFile extends Object implements IPerformanceLogs {
    
	/**
	 * returns array with stored statistics
	 * @return array statistics in two dimensions ([])(["count"],["average"])
	 */
    public function getBlocksList()
    {
    	$results = array();
    	$logDir = Environment::expand("%logDir%");
        if (!String::endsWith($logDir, "/")) {
        	$logDir = $logDir . "/";
        }
        if(!file_exists($logDir."CelebrioKernelTimers.log")) return array();

        $statisticsFile = NULL;
    	try {
    		$statisticsFile = new TextFile($logDir."CelebrioKernelTimers.log");
    	} catch (\FileNotFoundException $ex) {
            \Logger::getRootLogger()->error($logDir."CelebrioKernelTimers.log not found",$ex);
    		return 0;
    	}
    	
    	while($log = $statisticsFile->getLine()){
    		$firstDevider = strpos($log, "§");
    		$secondDevider = strpos($log, "§", $firstDevider+1);
    		$thirdDevider = strpos($log, "§", $secondDevider+1);
    		$block = substr($log, 0, $firstDevider-1);
    		$average = trim(substr($log, $firstDevider+2, ($secondDevider-1-strlen("§")-$firstDevider)));
    		$count = trim(substr($log, $secondDevider+2, ($thirdDevider-1-strlen("§")-$secondDevider)));
    		//$time = trim(substr($log, $thirdDevider+2));
    		$results[$block] = array(
	    				"count" => $count,
	    				"average" => $average);
    	}
    	return $results;
    }

}